const fs = require('fs');
const path = require('path');

const dirPath = process.argv[2];
const PROBLEMDIR_FILE_TYPE = ['.gz','.json','.txt','.log'];
let result = {};
divide(dirPath)
// console.log(result)



function divide(dirPath) {
    var r = /^\+?[0-9][0-9]*$/;
    const dirs = fs.readdirSync(dirPath).filter((dirname) => dirname.startsWith('problem_'));
    //const dirs = fs.readdirSync(dirPath).filter((dirname) => r.test(dirname));
    console.log(dirs);
    getResult(dirs);
    console.log(result)
    for (const [type, problemPathArr] of Object.entries(result)) {
        // console.log(type, problemPathArr)
        const typeDir = path.resolve(dirPath, type);
        try {
            fs.accessSync(typeDir);
        } catch (error) {
            fs.mkdirSync(typeDir);
        }
        
        problemPathArr.forEach(proPath => {
            const newProblemDir = path.join(typeDir, path.basename(proPath));
            try {
                fs.accessSync(newProblemDir);
            } catch (error) {
                fs.mkdirSync(newProblemDir);
            }
            const fileArr = fs.readdirSync(proPath);
            for (let j = 0; j < fileArr.length; j++) {
                const file = fileArr[j];
                const stats = fs.statSync(path.resolve(proPath, file));
                if (stats.isFile()) {
                    fs.renameSync(path.resolve(proPath, file), path.resolve(newProblemDir, file));
                }
            }
            fs.rmdirSync(proPath);
        });
    }
}

function getResult(dirs) {
    for (let i = 0; i < dirs.length; i++) {
        const problemDirPath = path.resolve(dirPath, dirs[i]);
        const typeName = getProblemType(problemDirPath);
        // console.log(typeName);
        if (result[typeName]) {
            result[typeName].push(problemDirPath);
        } else {
            result[typeName] = [problemDirPath];
        }
    }
}


function getProblemType(problemDirPath) {
    const fileNames = fs.readdirSync(problemDirPath);
    // console.log(fileNames)
    const typeFileName = fileNames.filter(name => !PROBLEMDIR_FILE_TYPE.includes(path.extname(path.resolve(problemDirPath, name))))[0];

    if (!typeFileName) {
        // throw new Error(`${problemDirPath}路径下没有错误日志文件`);
        return "others"
    }
    // console.log(typeFileName)
    return typeFileName.substring(0, typeFileName.indexOf('-'));
}